package com.xy.smartsms.adapter;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.xy.smartsms.facade.SmsProcessFacade;
import com.xy.smartsms.manager.PublicInfoManager;
import com.xy.smartsms.util.BitmapLoader;
import com.xy.smartsms.util.CommonUtils;
import com.xy.smartsms.util.Log;
import com.xy.smartsms.util.TimeUtils;
import com.xy.smartsms.web.SdkWebViewManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.cmcc.online.smsapi.sdk.db.entity.MatchCacheManager;
import cn.cmcc.online.smsapi.sdk.util.DuoquUtils;
import cn.cmcc.online.smsapi.sdk.util.PopupUtil;
import cn.cmcc.online.smsapi.sdk.util.XyUtil;
import cn.cmcc.online.smsapi.ui.manager.IDataCallback;
import cn.cmcc.online.smsapi.ui.manager.IDataExchange;
import cn.cmcc.online.smsapi.ui.model.ActionData;
import cn.cmcc.online.smsapi.ui.model.FlightData;
import cn.cmcc.online.smsapi.ui.model.TrainData;
import cn.cmcc.online.smsapi.ui.web.IActivityForWebView;
import cn.cmcc.online.smsapi.ui.web.IActivityParamForJS;
import cn.cmcc.online.smsapi.util.ParseManager;
import cn.cmcc.online.smsapi.util.SdkCallBack;

/**
 * Created by admin on 2017/6/22.
 */

public class DataExchangeImpl implements IDataExchange {
    private static final String TAG = "DataExchangeImpl";

    private static final String ACTION_SELECT_STATION = "cn.cmcc.online.TrainStationSelectedReceiver";
    private MyBroadcastReceiver mBroadcastReceiver = null;
    private IDataCallback<JSONObject> mTrainInfoListener;

    private static DataExchangeImpl sDataExchangeImpl = null;
    private BitmapLoader mBitmapLoader = null;
    private Context mContext = null;
    private Handler mHandler = new Handler(Looper.getMainLooper());

    private DataExchangeImpl(Context context) {
        mContext = context;
        mBitmapLoader = BitmapLoader.getInstance(mContext);
        PublicInfoManager.getInstance(mContext);
        registerReceiver();
    }

    public static DataExchangeImpl getInstance() {
        return sDataExchangeImpl;
    }

    public static DataExchangeImpl getInstance(Context context) {
        synchronized (DataExchangeImpl.class) {
            if (sDataExchangeImpl == null) {
                sDataExchangeImpl = new DataExchangeImpl(context);
            }
        }

        return sDataExchangeImpl;
    }

    private class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_SELECT_STATION.equals(action)) {
                try {
                    String key = intent.getStringExtra("JSONDATA");
                    if (TextUtils.isEmpty(key)) {
                        return;
                    }

                    JSONObject resultObj = new JSONObject(key);
                    mTrainInfoListener.onReady(IDataCallback.SUCCESS, resultObj);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void registerReceiver() {
        mBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_SELECT_STATION);
        mContext.registerReceiver(mBroadcastReceiver, intentFilter);
    }

    @Override
    public void processAction(Context activityContext, ActionData action) {
        SmsProcessFacade.getInstance().processAction((Activity) activityContext, action.getContent(), action.getExtra());
    }

    @Override
    public void setTrainInfoListener(IDataCallback<JSONObject> callback) {
        mTrainInfoListener = callback;
    }

    @Override
    public void getTrainInfo(TrainData data) {
        try {
            long stamp = TimeUtils.buildStamp(data.getReceiveTime(), data.getArriveDate(), data.getArriveTime());
            data.setArriveDateWeb(TimeUtils.stampToString(stamp, "yyyy-MM-dd"));
            JSONObject toWebObj = data.getWebData();
            toWebObj.put("view_depart_date_time", TimeUtils.buildStamp(data.getReceiveTime(), data.getDepartDate(), data.getDepartTime()));
            toWebObj.put("checkString", data.getTrainNumber());
            toWebObj.put("type", "WEB_TRAIN_STATION_NEW");
            PopupUtil.startWebActivity(mContext, toWebObj, "", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void getFlightInfo(final FlightData data, final IDataCallback<FlightData> callback) {
        long stamp = TimeUtils.buildStamp(data.getReceiveTime(), data.getDepartDate(), data.getDepartTime());
        String flightDate = TimeUtils.stampToString(stamp, "yyyy-MM-dd");
        ParseManager.queryFlightData(data.getFlightNumber(), flightDate, null, new SdkCallBack() {
            @Override
            public void execute(Object... objects) {
                if (objects == null || objects.length < 2 || objects[1].toString().contains("error_code")) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onReady(IDataCallback.FAIL, null);
                        }
                    });
                    return;
                }

                try {
                    JSONArray jsonArray = new JSONArray((String) objects[1]);
                    OnlineFlightData flightData = null;
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject obj = jsonArray.optJSONObject(i);
                        flightData = new OnlineFlightData(obj);
                        if (flightData.isValid(data)) {
                            break;
                        }
                    }
                    final OnlineFlightData completeFlightData = flightData;
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onReady(IDataCallback.SUCCESS, completeFlightData);
                        }
                    });
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void getMetaInfo(JSONObject data, IDataCallback<JSONObject> callback) {
        String phoneNumber = data.optString("phoneNum");
        PublicInfoManager.getInstance().loadPublicInfo(phoneNumber, new PublicInfoManager.OnPublicInfoListener() {
            @Override
            public void onPublicInfo(String phone, String name, BitmapDrawable drawable, JSONObject data) {

            }
        }, true);
    }

    @Override
    public void updateCardInfo(JSONObject data) {
        String phoneNumber = data.optString("phoneNum");
        String msgId = data.optString("msgId");
        String msgContent = data.optString("sms_content");
        String titleNumber = data.optString("title_num");
        try {
            // clone first, in order to keep the json used in ui intact
            JSONObject result = new JSONObject(data.toString());
            result.remove("sms_content");
            result.remove("action");

            MatchCacheManager.updateMatchCacheManager(phoneNumber, titleNumber, msgId, result, msgContent);
        } catch (Throwable t) {
            Log.e(TAG, "updateCardInfo", t);
        }
    }

    @Override
    public BitmapDrawable getBitmap(String path) {
        return mBitmapLoader.loadBitmap(CommonUtils.hashKey(path), path, null);
    }

    @Override
    public IActivityParamForJS getJSManager(IActivityForWebView activityForWebView) {
        SdkWebViewManager sdkWebViewManager = new SdkWebViewManager(activityForWebView);
        return sdkWebViewManager;
    }

    @Override
    public boolean geOnOffByType(int type) {
        return ParseManager.geOnOffByType(type);
    }

    @Override
    public JSONArray getConfigByType(int type, String uiversion, Integer suportMenuId) {
        return ParseManager.getConfigByType(type, uiversion, suportMenuId);
    }

    @Override
    public int checkNetWork(Context context, int type) {
        return XyUtil.checkNetWork(context, type);
    }

    @Override
    public void openMap(Context context, String name, String address, Double longitude, Double latitude) {
        DuoquUtils.getSdkDoAction().openMap(context, name, address, longitude, latitude);
    }

    @Override
    public void getLocation(Context context, Handler handler) {
        DuoquUtils.getSdkDoAction().getLocation(context, handler);
    }
}
